<template>
  <div>
    <!-- {{ forminputsasync }} -->
<!--    <el-form ref="elFrom" :model="formdata" :rules="rules" v-bind="$attrs">-->
<!--      <component :is="$attrs.inline ? 'span' : 'el-row'" :gutter="20">-->
<!--        &lt;!&ndash; <template > &ndash;&gt;-->
<!--        &lt;!&ndash; {{ formdata }} &ndash;&gt;-->
<!--        <component-->
<!--          :is="$attrs.inline ? 'span' : 'el-col'"-->
<!--          v-for="(item, index) in forminputs"-->
<!--          :key="index"-->
<!--          :span="item.span ? item.span : colspan"-->
<!--        >-->
<!--          <slot :formdata="formdata" :item="item" :name="'slot' + item.value">-->
<!--            <el-form-item-->
<!--              :label="$z.$t(item.label)"-->
<!--              :label-width="item['labelwidth']"-->
<!--              :prop="item.value"-->
<!--            >-->
<!--              <el-select-->
<!--                v-if="item.type == 'select'"-->
<!--                v-model="formdata[item.value]"-->
<!--                :disabled="item.disabled"-->
<!--                filterable-->
<!--                :placeholder="-->
<!--                  item.placeholder ? $z.$t(item.placeholder) : $z.$t('请选择')-->
<!--                "-->
<!--                :readonly="item.readonly"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="itemoptions in optionsfn(item, formdata)"-->
<!--                  :key="itemoptions.value"-->
<!--                  :label="$z.$t(itemoptions.label)"-->
<!--                  :value="itemoptions.value"-->
<!--                />-->
<!--              </el-select>-->
<!--              <el-date-picker-->
<!--                v-else-if="item.type == 'datetimerange'"-->
<!--                v-model="formdata[item.value]"-->
<!--                :clearable="false"-->
<!--                :disabled-date="item.disabledDate"-->
<!--                :end-placeholder="-->
<!--                  item.endplaceholder-->
<!--                    ? $z.$t(item.endplaceholder)-->
<!--                    : $z.$t('结束日期')-->
<!--                "-->
<!--                :placeholder="item.placeholder"-->
<!--                :range-separator="-->
<!--                  item.rangeseparator ? $z.$t(item.rangeseparator) : $z.$t('至')-->
<!--                "-->
<!--                :shortcuts="shortcutsfn(item.shortcuts)"-->
<!--                :start-placeholder="-->
<!--                  item.startplaceholder-->
<!--                    ? $z.$t(item.startplaceholder)-->
<!--                    : $z.$t('开始日期')-->
<!--                "-->
<!--                style="width: 100%"-->
<!--                :type="item.itemtype ? item.itemtype : 'datetimerange'"-->
<!--              />-->
<!--              <el-date-picker-->
<!--                v-else-if="item.type == 'date'"-->
<!--                v-model="formdata[item.value]"-->
<!--                :placeholder="item.placeholder"-->
<!--                type="date"-->
<!--              />-->
<!--              <formimg-->
<!--                v-else-if="item.type == 'img'"-->
<!--                :data="formdata"-->
<!--                :disabled="item.disabled"-->
<!--                :input="item"-->
<!--                :readonly="item.readonly"-->
<!--                @setimgfn="setimgfn"-->
<!--              />-->
<!--              <el-button-->
<!--                v-else-if="item.type == 'pcs'"-->
<!--                :disabled="item.disabled"-->
<!--                :readonly="item.readonly"-->
<!--                style="width: 100%; min-width: 200px"-->
<!--                @click="pcsshowfn(item)"-->
<!--              >-->
<!--                {{ formdata[item.value + 'lookstr'] }}-->
<!--              </el-button>-->
<!--              <formexcel-->
<!--                v-else-if="item.type == 'excel'"-->
<!--                :disabled="item.disabled"-->
<!--                :input="item"-->
<!--                :readonly="item.readonly"-->
<!--                @setexcel="setexcel"-->
<!--              />-->

<!--              <el-switch-->
<!--                v-else-if="item.type == 'switch'"-->
<!--                v-model="formdata[item.value]"-->
<!--                active-value="1"-->
<!--                :disabled="item.disabled"-->
<!--                inactive-value="0"-->
<!--                :readonly="item.readonly"-->
<!--              />-->
<!--              <el-input-->
<!--                v-else-->
<!--                v-model="formdata[item.value]"-->
<!--                :class="{ padding5: item.span <= 6 }"-->
<!--                :disabled="item.disabled"-->
<!--                :placeholder="item.placeholder"-->
<!--                :readonly="item.readonly"-->
<!--                :type="item.type ? item.type : ''"-->
<!--              >-->
<!--                <template #prepend v-if="item.type == 'typew'">-->
<!--                  {{-->
<!--                    item.prevalue ? numfn(formdata[item.prevalue], 1) : '0'-->
<!--                  }}&nbsp;&nbsp;{{ $z.$t(item.dw) }}&nbsp;&nbsp;&nbsp;&nbsp;～-->
<!--                </template>-->

<!--                <template #append v-if="item.type == 'mpt'">-->
<!--                  <el-button-->
<!--                    icon="el-icon-map-location"-->
<!--                    @click="btnclickfn(item)"-->
<!--                  />-->
<!--                </template>-->
<!--                <template #append v-else-if="item.type == 'yzmbtn'">-->
<!--                  <el-button :loading="yzmbtnloading" @click="getWpassSmsfn">-->
<!--                    {{ yzmbtnstr }}-->
<!--                  </el-button>-->
<!--                  &lt;!&ndash; <el-button v-model="yzmbtnstr" @click="btnclickfn(item)" /> &ndash;&gt;-->
<!--                </template>-->
<!--                &lt;!&ndash; typew &ndash;&gt;-->
<!--                <template #append v-else-if="item.dw">-->
<!--                  {{ $z.$t(item.dw) }}-->
<!--                </template>-->
<!--              </el-input>-->
<!--            </el-form-item>-->
<!--          </slot>-->
<!--        </component>-->
<!--        &lt;!&ndash; </template> &ndash;&gt;-->
<!--      </component>-->

<!--      <slot></slot>-->
<!--    </el-form>-->
    <slot name="append"></slot>
<!--    <formpcs ref="pcsdialog" :title="$z.$t('区域选择')">-->
<!--      <span class="dialog-footer">-->
<!--        <el-button @click="$refs['pcsdialog'].showEdit(false)">-->
<!--          {{ $z.$t('取消') }}-->
<!--        </el-button>-->
<!--        <el-button type="primary" @click="pcsqdfn">-->
<!--          {{ $z.$t('确定') }}-->
<!--        </el-button>-->
<!--      </span>-->
<!--    </formpcs>-->

<!--    <formmpt ref="formmpt" :data="formdata" :item="tapitem" />-->
  </div>
</template>

<script>
  // import formpcs from '@/components/formpcs/index'
  // import formmpt from '@/components/formmpt/index'
  // import formimg from '@/components/formimg/index'
  // import formexcel from '@/components/formexcel/index'
  // import qs from 'qs'

  export default {
    name: 'Formz',
    components: {
      // formpcs,
      // formimg,
      // formmpt,
      // formexcel,
    },
    props: {
      inputs: {
        type: Array,
        default: () => {
          return []
        },
      },
      data: {
        type: Object,
        default: () => {
          return {}
        },
      },
      colspan: {
        type: [Number, String],
        default: 12,
      },
      defaultdatavalue: {
        type: Object,
        default: () => {
          return {}
        },
      },
    },
    emits: ['change'],
    data() {
      return {
        formdata: {},
        setitem: {},

        tapitem: {},
        watchforminputsfalg: true,
        forminput: [],
        yzmbtnstr: this.$z.$t('获取验证码'),
        yzmbtnloading: false,
        yzmstr: '',
      }
    },
    asyncComputed: {
      async forminputsasync() {
        let inputs = []
        for (let index = 0; index < this.inputs.length; index++) {
          const element = this.inputs[index]
          if (element.callbackasync) {
            let inputscallbacks = await element.callbackasync.call(
              this,
              this.formdata
            )
            inputs = inputs.concat(inputscallbacks)
          } else if (element.callback) {
            let inputscallbacks = element.callback.call(this, this.formdata)

            inputs = inputs.concat(inputscallbacks)
          } else {
            inputs.push(element)
          }
        }

        // let r = [...inputs].filter((e) => {
        //   return this.$z.inputif(e, this.formdata, this.$attrs)
        // })
        return inputs
      },
    },
    computed: {
      yzmfalg() {
        return this.$store.state.falg.yzmfalg
      },
      forminputs() {
        if (typeof this.forminputsasync != 'object' || !this.forminputsasync) {
          return []
        }
        let r = []

        this.$z
          .deepClone(this.forminputsasync)
          .filter((e) => {
            return this.$z.inputif(e, this.formdata, this.$attrs)
          })
          .forEach((e) => {
            if (e.type == 'yzm') {
              if (!this.yzmfalg) {
                let utelstr = this.$store.state.user.token.utel
                r.push({
                  label: this.$z.$t('预留电话'),
                  value: 'yzmbtn',
                  type: 'yzmbtn',
                  defaultValue: `${utelstr.substr(0, 3)}****${utelstr.substr(
                    -4
                  )}`,
                  readonly: 'readonly',
                })
                e.rule = e.rule ? e.rule : []
                let that = this
                e.rule.push(
                  {
                    required: true,
                    message: `请输入${e.label}`,
                    trigger: 'blur',
                  },
                  {
                    required: true,
                    message: `${e.label}错误`,
                    trigger: ['change', 'blur'],
                    validator(rule, value, callback) {
                      if (that.yzmstr != value) {
                        callback(new Error('error'))
                      } else {
                        callback()
                      }
                    },
                  }
                )
                r.push(e)
              }
            } else {
              r.push(e)
            }
          })
        return r
      },
      rules() {
        let r = {},
          clearValidatefalg = false
        if (typeof this.forminput == 'undefined' || !this.forminputs) {
          return r
        }
        this.forminputs.forEach((e) => {
          if (e.rule) {
            clearValidatefalg = true
            e.rule.forEach((e) => {
              e.message = this.$z.$t(e.message)
            })
            r[e.value] = e.rule
          }
        })
        if (clearValidatefalg) {
          this.$nextTick(() => {
            this.$refs.elFrom.clearValidate()
          })
        }
        return r
      },
    },
    watch: {
      formdata: {
        handler() {
          this.$emit('change', this.setnowdatafn())
        },
        deep: true,
      },
      forminputs: {
        async handler(nvalue, ovalue) {
          if (!nvalue) {
            nvalue = []
          }
          if (!ovalue) {
            ovalue = []
          }
          if (!this.watchforminputsfalg) {
            this.setformdatascallback()
            return
          }
          let n = this.$z.deepClone(nvalue)
          let o = this.$z.deepClone(ovalue)
          let edtinputs = new Set(
            n.filter((e) => {
              return !o.find((f) => {
                return qs.stringify(e) == qs.stringify(f)
              })
            })
          )
          if (edtinputs.size == 0) {
            return
          }
          this.$nextTick(async () => {
            let array = [...edtinputs]
            for (let index = 0; index < array.length; index++) {
              const element = array[index]
              await this.setformdatafn(element, this.formdata)
            }
          })
        },
        deep: true,
      },
      data: {
        handler: function () {
          this.settingfn()
        },
        deep: true,
      },
      inputs: {
        handler: function () {
          this.settingfn()
        },
        deep: true,
      },
    },
    beforeCreate() {},
    created() {
      this.settingfn()
    },
    mounted() {},
    methods: {
      shortcutsfn(data = []) {
        let r = this.$z.deepClone(data)
        return r.map((e) => {
          e.text = this.$z.$t(e.text)
          return e
        })
      },
      async getWpassSmsfn() {
        this.yzmbtnloading = true
        let yzm = await this.$store.dispatch('base/getWpassSms')

        this.yzmstr = yzm
        this.yzmbtnstrfn(60)
      },
      yzmbtnstrfn(time = 60) {
        time--
        this.yzmbtnstr = `${time}s` + this.$t.$z('后重新获取')
        if (time == 0) {
          this.yzmbtnstr = this.$t.$z(`重新获取`)
          this.yzmbtnloading = false
        } else {
          setTimeout(() => {
            this.yzmbtnstrfn(time)
          }, 1000)
        }
      },
      numfn(num, num1) {
        if (!num) {
          return ''
        }
        return parseFloat(num).add(num1)
      },
      setimgfn({ value, input }) {
        if (input.type == 'img') {
          this.formdata[input.value] = value
        }
      },
      setexcel({ value, input }) {
        this.formdata[input.value] = value
        this.$refs.elFrom.validateField(input.value)
      },

      async settingfn() {
        // this.$z.throttle(() => {
        //   this.watchforminputsfalg = false
        //   this.formdata = this.$z.deepClone(this.data)
        // }, 1)
      },
      async setformdatascallback() {
        const data = await this.setformdatasfn()

        this.formdata = this.$z.deepClone(data)
        this.$nextTick(() => {
          this.watchforminputsfalg = true
        })
      },
      btnclickfn: function (item) {
        this.tapitem = item
        if (item.type == 'mpt') {
          this.$refs.formmpt.show((data) => {
            if (data.dz) {
              this.formdata[item.value] = data.dz
            }
            this.formdata[item.mptvalue] = data.mpt
          })
        }
      },
      pcsqdfn: async function () {
        this.$refs['pcsdialog'].showEdit(false)
        let data = this.$refs['pcsdialog'].getCurrentNode()
        if (!data) {
          data = { id: '' }
        }

        this.formdata[this.setitem.value] = data.id
        this.formdata[this.setitem.value + 'lookstr'] = await this.pcsvaluefn(
          this.setitem
        )
        this.$refs.elFrom.clearValidate(this.setitem.value)
      },
      pcsshowfn: async function (item = {}) {
        this.setitem = item
        // this.pcsall = item.all == 1
        // if (item.all == 1) {
        //   this.formpcsid = this.formdata[this.setitem.value]
        // } else {
        //   let pcsdata = await this.$store.dispatch(
        //     'station/getstationone',
        //     this.formdata[this.setitem.value]
        //   )
        //   this.formpcsid = pcsdata[0]
        // }
        this.$refs['pcsdialog'].showEdit(
          true,
          this.setitem,
          this.formdata[this.setitem.value]
        )
      },
      async pcsvaluefn(item, data = this.formdata) {
        let str = String(data[item.value])
        if (!str || str == '') {
          str = item.defaultText ? item.defaultText : this.$z.$t('全部')
        } else {
          let array = str.split(','),
            pcss = []
          for (let index = 0; index < array.length; index++) {
            const element = array[index]
            let stationdata = await this.$store.dispatch(
              'station/getstationone',
              element
            )
            pcss = pcss.concat(stationdata)
          }

          str = pcss
            .map((e) => {
              return e.pcs
            })
            .join()
        }
        return str
      },
      async setformdatasfn() {
        return new Promise((resolve) => {
          if (!this.forminputs) {
            setTimeout(async () => {
              resolve(await this.setformdatasfn())
            })
            return
          }
          ;(async () => {
            let r = this.$z.deepClone(this.data)

            for (let index = 0; index < this.forminputs.length; index++) {
              let e = this.forminputs[index]
              if (e.valuecallbackasync) {
                r[e.value] = await e.valuecallbackasync(this.data)
              } else if (e.valuecallback) {
                r[e.value] = e.valuecallback(this.data)
              } else if (e.fl && r[e.value]) {
                r[e.value] = parseFloat(r[e.value]).div(e.fl).toString()
              } else if (
                typeof r[e.value] != 'undefined' &&
                typeof r[e.value] != 'string' &&
                typeof r[e.value] != 'object'
              ) {
                r[e.value] = r[e.value].toString()
              } else if (typeof e.defaultValue != 'undefined') {
                if (typeof r[e.value] == 'undefined') {
                  if (typeof e.defaultValue == 'object') {
                    r[e.value] = e.defaultValue
                  } else {
                    r[e.value] = e.defaultValue.toString()
                  }
                }
              } else if (typeof r[e.value] == 'undefined') {
                r[e.value] = ''
              }
              if (e.type == 'pcs') {
                r[e.value + 'lookstr'] = await this.pcsvaluefn(e, r)
              }
              if (e.type == 'mpt') {
                let getGetMappt = await this.$store.dispatch('mpt/getGetMappt')

                r[e.mptvalue] = r[e.mptvalue] ? r[e.mptvalue] : getGetMappt.mpt
              }
            }
            // return r
            resolve(r)
          })()
        })
      },
      async setformdatafn(e = {}, r = {}) {
        if (!this.watchforminputsfalg) {
          return
        }
        if (
          e.bindingzd &&
          typeof e.bindingzd == 'object' &&
          this.$attrs[e.bindingzd.attr] &&
          typeof this.$attrs[e.bindingzd.attr][e.bindingzd.zd] != 'undefined'
        ) {
          let rstr = this.$attrs[e.bindingzd.attr][e.bindingzd.zd]

          if (e.fl && rstr) {
            rstr = parseFloat(rstr).div(e.fl).toString()
          }
          r[e.value] = rstr
        } else if (typeof e.defaultValue != 'undefined') {
          r[e.value] = e.defaultValue.toString()
        } else if (typeof r[e.value] == 'undefined') {
          r[e.value] = ''
        } else {
          r[e.value] = r[e.value] ? r[e.value] : ''
        }
        if (e.type == 'mpt') {
          let getGetMappt = await this.$store.dispatch('mpt/getGetMappt')
          r[e.mptvalue] = r[e.mptvalue] ? r[e.mptvalue] : getGetMappt.mpt
        }
        if (e.type == 'pcs') {
          r[e.value + 'lookstr'] = await this.pcsvaluefn(e)
        }
      },
      optionsfn(item) {
        let options = item.option ? item.option : []
        options = options.filter((e) => {
          if (typeof e.if == 'string') {
            e.zhi = e.zhi ? e.zhi : []
            e.nozhi = e.nozhi ? e.nozhi : []
            let rno = e.nozhi.indexOf(this.formdata[e.if]) >= 0
            if (rno) {
              return false
            }
            if (e.zhi.length == 0) {
              return true
            }
            return e.zhi.indexOf(this.formdata[e.if]) >= 0
          } else if (typeof e.if == 'object' && e.if.length != 0) {
            return e.if.find((f) => {
              return f.zhi.find((zhif) => {
                return this.formdata[f.zd] == zhif
              })
            })
          } else {
            return true
          }
        })

        return options
      },
      setnowdatafn(validfalg = false) {
        let r = {}
        this.forminputs.forEach((e) => {
          let val = this.formdata[e.value]
          if (e.type == 'yzm') {
            if (validfalg) {
              this.$store.commit('falg/setyzmfalg', true)
            }
          } else if (e.type == 'datetimerange') {
            if (e.itemtype == 'datetimerange' || !e.itemtype) {
              e.values = e.values ? e.values : []
              if (e.values.length != 0) {
                r[e.values[0]] = this.$z.timeFormat(
                  val[0],
                  'yyyy-mm-dd hh:MM:ss'
                )
                r[e.values[1]] = this.$z.timeFormat(
                  val[1],
                  'yyyy-mm-dd hh:MM:ss'
                )
              }
            } else {
              if (val == '') {
                r[e.value] = val
              } else {
                r[e.value] = this.$z.timeFormat(val, 'yyyy-mm-dd')
              }
            }
          } else {
            if (e.fl && val) {
              val = parseFloat(val).mul(parseFloat(e.fl))
            }
            if (e.type == 'mpt') {
              r[e.mptvalue] = this.formdata[e.mptvalue]
            }
            r[e.value] = val
          }
        })
        return r
      },
      forceformdata(zd, value) {
        this.formdata[zd] = value
      },
      validate(fromfalg = false) {
        return new Promise((resolve) => {
          this.$refs.elFrom.validate((valid) => {
            if (valid) {
              let fromvalue = this.setnowdatafn(true)
              if (fromfalg) {
                let searchdata = {}
                for (let key in fromvalue) {
                  if (fromvalue[key] != '') {
                    searchdata[key] = fromvalue[key]
                  }
                }
                let r = {
                  data: this.$z.deepClone({
                    ...this.defaultdatavalue,
                    ...this.data,
                    ...fromvalue,
                  }),
                  formdata: fromvalue,
                  poropdata: this.$z.deepClone({ ...this.data }),
                  forminput: this.forminputs,
                  searchdata: searchdata,
                }
                resolve(r)
              } else {
                resolve(
                  this.$z.deepClone({
                    ...this.defaultdatavalue,
                    ...this.data,
                    ...fromvalue,
                  })
                )
              }
            } else {
              // reject();
            }
          })
        })
      },
      asyncupdate() {
        this.$asyncComputed.forminputsasync.update()
      },
      validateField(prop) {
        // this.formdata
        return new Promise((resolve) => {
          this.$refs.elFrom.validateField(prop, (p) => {
            if (!p) {
              resolve(this.formdata[prop])
            }
          })
        })
        // return this.$refs.elForm.validateField();
      },
    },
  }
</script>
<style lang="scss" scope>
  .el-input--small .el-input__inner {
    text-align: left;
  }
  .el-form-item__label {
    overflow: auto;
    white-space: nowrap;
  }
  .padding5 > * {
    padding: 0 5px;
  }
</style>
